import { ref, onMounted, onBeforeUnmount } from 'vue';

export function useScrollAnimation(options: {
  threshold?: number;
  root?: Element | null;
  rootMargin?: string;
} = {}) {
  const elements = ref<HTMLElement[]>([]);
  const observer = ref<IntersectionObserver | null>(null);

  // 添加元素到观察列表
  const observe = (el: HTMLElement) => {
    elements.value.push(el);

    // 如果已经初始化了observer，立即观察这个元素
    if (observer.value) {
      observer.value.observe(el);
    }
  };

  // 停止观察元素
  const unobserve = (el: HTMLElement) => {
    const index = elements.value.indexOf(el);
    if (index !== -1) {
      elements.value.splice(index, 1);
    }

    if (observer.value) {
      observer.value.unobserve(el);
    }
  };

  // 初始化IntersectionObserver
  onMounted(() => {
    const { threshold = 0.1, root = null, rootMargin = '0px' } = options;

    observer.value = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const element = entry.target as HTMLElement;
          element.classList.add('animate');

          // 如果只需要触发一次动画，观察完成后停止观察
          if (element.dataset.once === 'true') {
            unobserve(element);
          }
        } else {
          // 如果元素不在视口，并且不是'once'，则移除动画类
          const element = entry.target as HTMLElement;
          if (element.dataset.once !== 'true') {
            element.classList.remove('animate');
          }
        }
      });
    }, {
      threshold,
      root,
      rootMargin
    });

    // 观察所有已添加的元素
    elements.value.forEach(el => {
      observer.value?.observe(el);
    });
  });

  // 清理
  onBeforeUnmount(() => {
    if (observer.value) {
      observer.value.disconnect();
      observer.value = null;
    }
  });

  return {
    observe,
    unobserve,
    elements
  };
} 